﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using CustomsSystem.BLL;
using System.Web.UI.WebControls;
using Maticsoft.Common;
using CustomsSystem.Model;

namespace WEB.T_bill
{
    public partial class receivables: System.Web.UI.Page
    {
     
        protected void Page_Load(object sender, EventArgs e)
        {
            //基础信息绑定
            if (Session["sheetID"] != null && Session["sheetID"].ToString() != "" )
            {
                infoBind();
            } 
            string a = lbsheetID .Text;
            Session["billTypeID"] = "1";
            if (!IsPostBack)
            {
                ddlTemplate.DataSource = GetTemplate();
                ddlTemplate.DataTextField = "templetName";
                ddlTemplate.DataValueField = "ID";
                ddlTemplate.DataBind();
                  
                if (lbsheetID .Text != "" && lbsheetID .Text != null)
                {
                    GetInfo(int.Parse(a), 1); 
                }
                if (gvReceivables.Rows.Count < 1)
                { Bind();}
               
            }
       

            if (gvReceivables.Rows.Count > 1)
            { }
            else
            {
                if (((HiddenField)gvReceivables.Rows[0].FindControl("hfauditEmpID")).Value.Trim() != null && ((HiddenField)gvReceivables.Rows[0].FindControl("hfauditEmpID")).Value.Trim() != "0")
                {
                    ddlTemplate.Visible = false;//当该单已被审核，则无需显示模板
                    lbmuban.Visible = false;
                }
            }
         
        }
        /// <summary>
        /// 绑定个空表--费用表
        /// </summary>
        protected void Bind()
        {

            DataTable dt1 = new DataTable("Table1");
            dt1.Columns.Add("编号", typeof(String));
            dt1.Columns.Add("feeTypeID", typeof(String));
            dt1.Columns.Add("sfeeAmount", typeof(String));
            dt1.Columns.Add("empID", typeof(String));
            dt1.Columns.Add("remark", typeof(String));
            dt1.Columns.Add("payedID", typeof(String));
            dt1.Columns.Add("auditEmpID", typeof(String));
            dt1.Columns.Add("afeeAmount", typeof(String));
            //默认5行
            DataRow dr1 = dt1.NewRow();
            DataRow dr2 = dt1.NewRow();
            DataRow dr3 = dt1.NewRow();
            DataRow dr4 = dt1.NewRow();
            DataRow dr5 = dt1.NewRow();
            dr1[1] = "0";
            dr1[2] = "";
            dr1[3] = "";
            dr1[5] = "0";
            dr1[6] = "0";
            dr1[7] = "0";

            dr2[1] = "0";
            dr2[2] = "";
            dr2[3] = "0";
            dr2[5] = "0";
            dr2[6] = "0";
            dr2[7] = "0";

            dr3[1] = "0";
            dr3[2] = "";
            dr3[3] = "0";
            dr3[5] = "0";
            dr3[6] = "0";
            dr3[7] = "0";

            dr4[1] = "0";
            dr4[2] = "";
            dr4[3] = "0";
            dr4[5] = "0";
            dr4[6] = "0";
            dr4[7] = "0";

            dr5[1] = "0";
            dr5[2] = "";
            dr5[3] = "0";
            dr5[5] = "0";
            dr5[6] = "0";
            dr5[7] = "0";
            dt1.Rows.Add(dr1);
            dt1.Rows.Add(dr2);
            dt1.Rows.Add(dr3);
            dt1.Rows.Add(dr4);
            dt1.Rows.Add(dr5);
            dt1.AcceptChanges();
            gvReceivables.DataSource = dt1;
            gvReceivables.DataBind();
        }

        /// <summary>
        /// 获取基础信息
        /// </summary>
        protected void infoBind()
        {
            int i = int.Parse(Session["sheetID"].ToString());
            CustomsSystem.Model.sheetInfo si = new CustomsSystem.BLL.SheetInfoManage().GetModel(i);
            if (si != null)
            {
                lbsheetID.Text = Session["sheetID"].ToString();
                lblCID.Text = Session["CustomerName"].ToString();
                lbladingBillNO.Text = si.ladingBillNo;
                lbagencyDate.Text = si.agencyDate.ToShortDateString();
                lbgoodsName.Text = si.goodsName;
                lbshipName.Text = si.shipName;
            }

        }

      

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
           //验证费用是否同类
            for (int j = 0; j < gvReceivables.Rows.Count-1;j++)
            {
                for (int n = 1; n < gvReceivables.Rows.Count; n++)
                {
                    if (((DropDownList)gvReceivables.Rows[j].Cells[1].FindControl("ddlfeeTypeID")).SelectedValue == ((DropDownList)gvReceivables.Rows[n].Cells[1].FindControl("ddlfeeTypeID")).SelectedValue && ((DropDownList)gvReceivables.Rows[j].Cells[1].FindControl("ddlfeeTypeID")).SelectedValue != "0"&&n!=j)
                    {
                        goto end;
                    }
                }
            }
            CustomsSystem.Model.Bill bill = new CustomsSystem.Model.Bill();
            bill.auditEmpID = ((HiddenField)gvReceivables.Rows[0].FindControl("hfauditEmpID")).Value.Trim ().ToString();
            if (bill.auditEmpID != "0")
            {
                Response.Write("<script>alert('该单已被审核，请反审核后再作修改');history.go(-2);</script>");
          
            }
            else
            {
                string a = lbsheetID .Text;//要删除或者更新，先删除数据库里的数据，然后再保存
                BillManage bll = new BillManage();
                bll.Delete(int.Parse(a), 1);




                //下面是保存gv的数据

                int cid; string sf;
                string cName;
                cName = lblCID.Text.Trim();
                CustomsSystem.Model.Customer cus = new CustomsSystem.BLL.CustomerManage().GetModel(cName);
                cid = cus.ID;

                for (int i = 0; i < gvReceivables.Rows.Count; i++)
                {

                  
                    bill.feeTypeID = ((DropDownList)gvReceivables.Rows[i].Cells[1].FindControl("ddlfeeTypeID")).SelectedValue;
                    if (bill.feeTypeID != "0")
                    {
                        bill.sheetID = int.Parse(lbsheetID.Text.Trim());
                        bill.cID = cid;
                        bill.billTypeID = 1;
                        sf = ((TextBox)gvReceivables.Rows[i].Cells[2].FindControl("tbfeeAmount")).Text;
                        if (sf == "" || sf == null)
                            sf = "0";
                        bill.sfeeAmount = decimal.Parse(sf);
                        //bill.empID = ((DropDownList)gvReceivables.Rows[i].Cells[3].FindControl("ddlempID")).SelectedValue; ;
                        bill.inputDate = DateTime.Now;
                        bill.inputEmpNo = Session["EmpNo"].ToString();
                        // bill.inputEmpNo = Session["empNo"].ToString();
                        bill.remark = ((TextBox)gvReceivables.Rows[i].Cells[3].FindControl("tbremark")).Text.Trim().ToString();
                        string AF = ((HiddenField)gvReceivables.Rows[i].FindControl("hfafeeAmount")).Value.ToString();
                        if (AF != null&&AF !="")
                        { bill.afeeAmount = decimal.Parse(AF); }
                        else bill.afeeAmount = 0;
                        bill.empID = "0";
                        bill.auditEmpID = "0";
                        bill.payedID = 0;
                        bll.Add(bill);
                    }
                   
                   

                }
                Response.Write("<script>alert('保存成功！');history.go(-1);</script>");
             
            }
        end: MessageBox.Show(this,"费用重复，请修改费用类别！");
        }

        

     /// <summary>
     /// 获取费用类别
     /// </summary>
     /// <returns></returns>
       public  DataTable GetFeeType()
        { 
            FeeTypeManage feeTypeManage=new FeeTypeManage ();
            DataSet ds = feeTypeManage.GetFeeList(" feeType =0 ");
            DataTable dt = ds.Tables[0];
            return dt;
           
        }
        /// <summary>
        /// 获取人员表
        /// </summary>
        /// <returns></returns>
       public DataTable GetEmpNum()
       {
           CustomsSystem.BLL.UserManage UserManage = new UserManage();
           DataSet ds = UserManage.GetAllList();
           DataTable dt = ds.Tables[0];
           return dt;

       }
      

   
        /// <summary>
        /// 获取已填入的数据
        /// </summary>
        /// <returns></returns>
       protected DataTable GetDataFromGrid()
       {
           DataTable dt1 = new DataTable("Table1");
           dt1.Columns.Add("编号");
           dt1.Columns.Add("feeTypeID");
           dt1.Columns.Add("sfeeAmount");
           dt1.Columns.Add("empID");
           dt1.Columns.Add("remark");
           dt1.Columns.Add("payedID", typeof(String));
           dt1.Columns.Add("auditEmpID", typeof(String));
           dt1.Columns.Add("afeeAmount", typeof(String));
           for (int i = 0; i < gvReceivables.Rows.Count; i++)
           {
               GridViewRow gRow = gvReceivables.Rows[i];
               DataRow newRow = dt1.NewRow();
               newRow[0] = i + 1;
               newRow[1] = ((DropDownList)gRow.FindControl("ddlfeeTypeID")).SelectedValue;
               newRow[2] = ((TextBox)gRow.FindControl("tbfeeAmount")).Text;
              // newRow[3] = ((DropDownList)gRow.FindControl("ddlempID")).SelectedValue;
               newRow[4] = ((TextBox)gRow.FindControl("tbremark")).Text;
               newRow[5] = int.Parse(((HiddenField)gRow.FindControl("hfpayedID")).Value.ToString());
               newRow[6] = ((HiddenField)gRow.FindControl("hfauditEmpID")).Value;
               newRow[7] = decimal.Parse(((HiddenField)gRow.FindControl("hfafeeAmount")).Value.ToString());
               dt1.Rows.Add(newRow);


           }
           dt1.AcceptChanges();
           
           return dt1;
       }
       /// <summary>
       /// 增加一行
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       protected void btnAddRow_Click(object sender, EventArgs e)
       {
           
           DataTable dt = GetDataFromGrid();
           DataRow dr = dt.NewRow();
           
           dr[1] = "0";
           dr[2] = "";
           dr[3] = "0";
           dr[5] = "0";
           dr[6] = "0";
           dr[7] = "0";
           dt.Rows.Add(dr);
           dt.AcceptChanges();
           gvReceivables.DataSource = dt;
           gvReceivables.DataBind();

       }

        /// <summary>
        /// 获取审核人和制单人信息
        /// </summary>
        /// <param name="sheetID"></param>
        /// <param name="billTypeID"></param>
       public void GetInfo(int sheetID, int billTypeID)
       {
           BillManage bll = new BillManage();

           DataSet ds = bll.GetList(sheetID, billTypeID);

           gvReceivables.DataSource = ds;
           gvReceivables.DataBind();
          
           if (ds.Tables [0].Rows .Count >1)
           {
               string empname = ds.Tables[0].Rows[0][7].ToString();
               string audit = ds.Tables[0].Rows[0][9].ToString();
               if (empname != null && empname != "")
               {
                   CustomsSystem.Model.Info_emp emp = new CustomsSystem.BLL.EmpManage().GetModel(empname);
                   if (emp != null)
                       lblinputEmpNum.Text = emp.UserName;
               }
               else
               {
                   if (Session["EmpNo"] != null && Session["UserName"] != null)
                       lblinputEmpNum.Text = Session["UserName"].ToString();
               }
               if (audit != null && audit != "")
               {
                   CustomsSystem.Model.Info_emp au = new CustomsSystem.BLL.EmpManage().GetModel(audit);
                   if (au != null)
                   { lbaudit.Text = "审核人：" + au.UserName;
                    ///Button4.Text = "反审核"; 
                    }
                   else { lbaudit.Text = ""; Button4.Text = "审核"; }
               }
           }
       }
       /// <summary>
       /// 隐藏列
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       protected void  gvReceivables_RowDataBound(object sender, GridViewRowEventArgs e)
       {
         // e.Row.Cells[3].Visible = false;//让第3列不可见
       }


        /// <summary>
        /// 选择模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void ddlTemplate_SelectedIndexChanged(object sender, EventArgs e)
       {
           if (ddlTemplate.SelectedValue != "0")
           {
               Fee_templetdetailManage ftdm = new Fee_templetdetailManage();
               DataSet ds = ftdm.GetTList(" feetemplet_ID=" + ddlTemplate.SelectedValue);
               DataTable dt = ds.Tables[0];
               gvReceivables.DataSource = dt;
               gvReceivables.DataBind();
           }
       }

        /// <summary>
        /// 载入模板列表
        /// </summary>
        /// <returns></returns>
       public DataTable GetTemplate()
       {
           int i = int.Parse(Session["sheetID"].ToString());
           CustomsSystem.Model.sheetInfo sheet = new CustomsSystem.BLL.SheetInfoManage().GetModel(i);
            
           DataTable dt = new DataTable();
           DataSet ds = new DataSet();
           Fee_templetManage ftm = new Fee_templetManage();
           ds = ftm.GetList(" typeid=1 and goodsType=" + sheet.goodsType);
           dt = ds.Tables[0];
           return dt;
 
       }

       #region 新增的四个按钮
       /// <summary>
        /// 审核或反审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void Button4_Click(object sender, EventArgs e)
       {
           if (Button4.Text == "审核")
           {
               Bill model = new Bill();
               BillManage bll = new BillManage();
               model.billTypeID = int.Parse(Session["billTypeID"].ToString());
               model.sheetID = int.Parse(Session["sheetID"].ToString());
               model.auditEmpID = Session["EmpNo"].ToString();
               model.auditdate = DateTime.Today;
               if (bll.UpdateAudit(model))
                   MessageBox.ShowAndRedirect(this, "审核成功", "receivables.aspx");
               else
                   MessageBox.ShowAndRedirect(this, "审核失败", "receivables.aspx");
           }
           if (Button4.Text == "反审核")
           {
               Bill model = new Bill();
               BillManage bll = new BillManage();
               model.billTypeID = int.Parse(Session["billTypeID"].ToString());
               model.sheetID = int.Parse(Session["sheetID"].ToString());
               model.auditEmpID = "0";
               model.auditdate = DateTime.Today;
               if (bll.UpdateAudit(model))
                   MessageBox.ShowAndRedirect(this, "反审核成功", "receivables.aspx");
               else
                   MessageBox.ShowAndRedirect(this, "反审核失败", "receivables.aspx");
           }
       }

        /// <summary>
        /// 应付款录入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void Button1_Click(object sender, EventArgs e)
       {
           Response.Redirect("payment.aspx");
       }

        /// <summary>
        /// 实收销账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void Button2_Click(object sender, EventArgs e)
       {
           Response.Redirect("actualReceivables.aspx");
       }

        /// <summary>
        /// 实付销账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void Button3_Click(object sender, EventArgs e)
       {
           Response.Redirect("actualPayment.aspx");
       }
       #endregion 
        // /// <summary>
       // /// 跳转到票结
       // /// </summary>
       // /// <param name="sender"></param>
       // /// <param name="e"></param>
       //protected void btnMakeE_Click(object sender, EventArgs e)
       //{
       //    Session["sheetID"] = int.Parse(lbsheetID .Text.Trim ());
       //    Response.Redirect("detailedAccount.aspx");
       //}
    }
}